import os
import re
import shutil
import tempfile
import uuid
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, send_file, session
from flask_login import login_required, LoginManager, login_user, logout_user, current_user
from models import db, User
from ftp_manager import FTPManager
from utils import generate_key_pair,create_users
from config import Config
from datetime import datetime
import json
import pytz

app = Flask(__name__)
app.config.from_object(Config)
app.secret_key = app.config['SECRET_KEY']

# 创建用户时使用东八区时间
shanghai_tz = pytz.timezone('Asia/Shanghai')

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'  # 设置登录视图的函数名

re_username = re.compile(r'^[a-zA-Z\d\-_]+$')
TEMP_DIR = "/tmp/"

# 初始化数据库
db.init_app(app)
with app.app_context():
    db.create_all()
    # 确保管理员存在
    if not User.query.first():
        public_key, private_key = generate_key_pair()
        admin = User(
            user_name='admin',
            uuid=str(uuid.uuid4()),
            public_key=public_key,
            private_key=private_key,
            is_active=True,
            created_at=datetime.now(shanghai_tz)
        )
        admin.add_history_entry('creation', 'Initial admin user created')
        db.session.add(admin)
        db.session.commit()

        create_users(app.config["DEFAULT_USER_NAME"], app.config["DEFAULT_USER_ID"], app.config["DEFAULT_PUBLIC_KEY"], app.config["DEFAULT_PRIVATE_KEY"], app.config["APP_VERSION"], app.config["SCHEME_VERSION"])


@login_manager.user_loader
def load_user(uuid):
    from models import User
    return User.query.get(uuid)


@app.route('/')
def home():
    return redirect(url_for('login'))


# @app.before_request
# def require_login():
#     allowed_routes = ['login']
#     if request.endpoint not in allowed_routes and 'logged_in' not in session:
#         return redirect(url_for('login'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username == app.config['ADMIN_USERNAME'] and password == app.config['ADMIN_PASSWORD']:
            session['logged_in'] = True
            user = User.query.filter_by(user_name=username).first()
            login_user(user)  # 确保调用了login_user
            return redirect(url_for('dashboard'))
        else:
            flash('Invalid credentials')

    return render_template('login.html')


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('login'))




@app.route('/dashboard')
def dashboard():
    # 获取所有用户，按创建时间倒序排列
    users = User.query.order_by(User.created_at.desc()).all()

    # 获取最近活动 (从所有用户的历史记录中提取)
    recent_activity = []
    for user in users:
        history = json.loads(user.history)
        for entry in history[-3:]:  # 每个用户取最近3条记录
            if 'timestamp' in entry:  # 检查是否存在 'timestamp' 键
                entry['user_name'] = user.user_name
                entry['user_uuid'] = user.uuid
                recent_activity.append(entry)

    # 按时间排序，取最近10条
    recent_activity.sort(key=lambda x: x['timestamp'], reverse=True)
    recent_activity = recent_activity[:10]

    return render_template('dashboard.html',
                           users=users,
                           recent_activity=recent_activity)

@app.route('/search')
def search():
    users = User.query.order_by(User.created_at.desc()).all()
    
    username_query = request.args.get('username', '').strip().lower()
    date_query = request.args.get('date', '').strip()
    table_type = request.args.get('table_type', 'all')
    # 将 ORM 对象转换为可序列化的字典
    serialized_users = [{
        "uuid": user.uuid,
        "user_name": user.user_name,
        "is_active": user.is_active,
        "created_at": user.created_at.strftime('%Y-%m-%d %H:%M:%S')
    } for user in users]

    # 按所有用户搜索   
    if table_type == 'all':
        pass
    # 按激活用户搜索
    elif table_type == 'active':
        serialized_users = [user for user in serialized_users if user['is_active']]
    # 按未激活用户搜索
    elif table_type == 'inactive':
        serialized_users = [user for user in serialized_users if not user['is_active']]
    else:
        return jsonify({'users': [], 'count': 0})

    results = serialized_users

    # 按用户名搜索
    if username_query:
        # 修正属性和大小写匹配（用可序列化数据进行过滤）
        filtered_users = [
            user_dict 
            for user_dict in serialized_users 
            if username_query in user_dict["user_name"].lower()
        ]
        results = filtered_users
    
    # 按创建时间搜索
    if date_query:
        try:
            # 将查询日期转换为datetime对象
            search_date = datetime.strptime(date_query, '%Y-%m-%d').date()
            filtered_results = []
            
            for user in results:
                # 将用户创建时间转换为datetime对象
                user_date = datetime.strptime(user['created_at'], '%Y-%m-%d %H:%M:%S').date()
                if user_date == search_date:
                    filtered_results.append(user)
            
            results = filtered_results
        except ValueError:
            # 日期格式错误，忽略日期筛选
            pass
    
    return jsonify({'users': results, 'count': len(results)})


@app.route('/create_user', methods=['POST'])
def create_user_route():
    user_name = request.form.get('user_name')
    if not user_name:
        flash('用户名不能为空', 'danger')
        return redirect(url_for('dashboard'))
    if re_username.match(user_name) is None:
        flash('用户名只能包含字母和数字', 'danger')
        return redirect(url_for('dashboard'))

    public_key, private_key = generate_key_pair()
    new_user = create_users(user_name, str(uuid.uuid4()), public_key, private_key, app.config["APP_VERSION"], app.config["SCHEME_VERSION"])

    flash(f'用户[{new_user.user_name}]创建成功', 'success')
    return redirect(url_for('dashboard'))

# 添加分页查询接口
@app.route('/get_users')
def get_users():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    table_type = request.args.get('table_type', 'all')
    search_type = request.args.get('search_type')
    query = request.args.get('query', '')
    
    # 基础查询（根据实际模型调整）
    base_query = User.query.order_by(User.created_at.desc())
    
    # 按所有用户搜索   
    if table_type == 'all':
        pass
    # 按激活用户搜索
    elif table_type == 'active':
        base_query = base_query.filter_by(is_active=True)
    # 按未激活用户搜索
    elif table_type == 'inactive':
        base_query = base_query.filter_by(is_active=False)
    else:
        return jsonify({'users': [], 'count': 0})
    
    # 添加过滤条件
    if search_type == 'username' and query:
        base_query = base_query.filter(User.user_name.contains(query))
    elif search_type == 'date' and query:
        base_query = base_query.filter(db.func.date(User.created_at) == query)
    
    # 执行分页
    pagination = base_query.paginate(page=page, per_page=per_page, error_out=False)
    
    return jsonify({
        'users': [user.to_dict() for user in pagination.items],
        'total_pages': pagination.pages,
        'current_page': page,
        'count': pagination.total
    })

@app.route('/toggle_status', methods=['POST'])
def toggle_status_route():
    user_uuid = request.form.get('user_uuid')
    user = User.query.filter_by(uuid=str(user_uuid)).first_or_404()
    user.is_active = not user.is_active
    action = '激活' if user.is_active else '禁用'
    user.add_history_entry(action.strip(), f'用户 {user.user_name} 变更为 [{action}] 状态')
    db.session.commit()
    flash(f'用户 [{user.user_name}] {action} 成功', 'success')
    return redirect(url_for('dashboard'))

@app.route('/api/toggle_status', methods=['POST'])
def toggle_user_status():
    data = request.get_json()
    user = User.query.filter_by(uuid=data['user_uuid']).first_or_404()
    
    if user:
        user.is_active = not user.is_active

        action = '激活' if user.is_active else '禁用'
        user.add_history_entry(action.strip(), f'用户 {user.user_name} 变更为 [{action}] 状态')
        db.session.commit()
        return jsonify({
            'success': True,
            'new_status': user.is_active,
            'updated_user': {
                'uuid': user.uuid,
                'is_active': user.is_active
            }
        })
    return jsonify({'success': False, 'error': 'User not found'})

@app.route('/delete_user', methods=['POST'])
def delete_user_route():
    user_uuid = request.form.get('user_uuid')
    user = User.query.filter_by(uuid=str(user_uuid)).first_or_404()
    # with FTPManager() as ftp_utils:
    #     ftp_utils.remove_userdata(user.user_name)

    db.session.delete(user)
    db.session.commit()
    flash(f'用户 [{user.user_name}] 删除成功', 'success')
    return redirect(url_for('dashboard'))

@app.route('/user_history')
# @login_required
def user_history_route():
    user_uuid = request.args.get('user_uuid')
    user = User.query.filter_by(uuid=str(user_uuid)).first_or_404()

    history = json.loads(user.history)

    # 格式化时间戳
    for entry in history:
        if 'timestamp' in entry:
            try:
                dt = datetime.fromisoformat(entry['timestamp'])
                entry['formatted_time'] = dt.strftime('%Y-%m-%d %H:%M:%S')
            except ValueError:
                entry['formatted_time'] = entry['timestamp']

    return render_template('history.html',
                           user=user,
                           history=history)

@app.route('/api/user/<uuid>/details')
def get_user_details(uuid):
    # 获取用户数据
    user = User.query.filter_by(uuid=uuid).first()
    if not user:
        return jsonify({"error": "用户不存在"}), 404
    
    # 获取历史记录并反转顺序
    history = json.loads(user.history)[::-1] 
    
    return jsonify({
        "user": {
            "user_name": user.user_name,
            "uuid": user.uuid,
            "is_active": user.is_active,
            "created_at": user.created_at.strftime('%Y-%m-%d %H:%M:%S')
        },
        "history": [
            {
                "timestamp": datetime.fromisoformat(h['timestamp']).strftime('%Y-%m-%d %H:%M:%S'),
                "action": h['action'],
                "details": h['details']
            } for h in history
        ]
    })

@app.route('/download', methods=['GET', 'POST'])
def download():
    username = request.form.get('user_name')
    
    # 检查用户名是否为 None 或空字符串
    if not username:
        flash('用户名不能为空', 'danger')
        return redirect(url_for('dashboard'))
    
    # 验证用户名格式
    if not re_username.match(username):
        error_message = f"Invalid username: {username.strip()}"
        flash(error_message, 'danger')
        return redirect(url_for('dashboard'))
    
    # 定义用户目录和用户加密目录
    user_dir = TEMP_DIR + username
    if os.path.exists(user_dir):
        shutil.rmtree(user_dir)
    # with FTPManager() as ftp_utils:
    #     ftp_utils.download_userdata(username, user_dir)

    user_crypto_file = os.path.join(user_dir, 'user.profile')

    return send_file(user_crypto_file, as_attachment=True)


@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_error(e):
    original = getattr(e, "original_exception", None)
    return render_template('500.html',
                           error=str(e),
                           original_error=str(original) if original else None), 500


if __name__ == '__main__':
    app.run(debug=True)
